import { ref, computed } from 'vue';
import { isNull, clog, clone } from '/@/utils';
import { useInitDataSingleton } from './shared';
import { SysOrgApi, SysOrgAllOutput } from '/@/api/bas/sysOrg';
import { loginInfo } from './LoginInfo';

const { list, initList: initOrgList } = useInitDataSingleton<SysOrgAllOutput>(SysOrgApi.all);

// 科室资料, 必须在登录后初始化
export { initOrgList };

// 院区列表
export const yuanQuList4Login = computed(() => {
	return list.value.filter((item) => item.pid == 0 && item.isEnabled) ?? [];
});

// 院区列表
export const yuanQuList = computed(() => {
	return list.value.filter((item) => item.pid == 0 && item.tenantId == loginInfo.value.tenantId) ?? [];
});

// 协议医院
export const getXieYiYiYuanList4Select = () => {
	// 1300000000001 之外的租户才是协议医院的租户,租户内的顶级组织(item.pid == 0)就是协议医院名称
	var arr = list.value.filter((item) => item.pid == 0 && item.tenantId != 1300000000001) ?? [];
	return arr.map((item) => {
		return {
			tenantId: item.tenantId,
			id: item.id,
			mingCheng: item.name,
			isEnabled: item.isEnabled,
		};
	});
};

// 获取协议医院
export const getXieYiYiYuan = (tenantId: number): SysOrgAllOutput => {
	return list.value.find((item) => item.pid == 0 && item.tenantId == tenantId) ?? ({} as SysOrgAllOutput);
};

// 科室列表
export const keShiList = computed(() => {
	return list.value.filter((item) => item.pid > 0) ?? [];
});

// 根据id获取科室名称
export function getOrgName(id: number) {
	let name = list.value.find((item) => item.id == id)?.name ?? '';
	return name;
}

// 查找组织机构根节点,查找科室根节点(院区)
export function findOrgRoot(id: number): SysOrgAllOutput {
	const node = list.value.find((node) => node.id === id);
	if (!node || node.pid == 0) {
		// If pid==0, it's the root
		return node ? clone(node) : ({} as SysOrgAllOutput);
	}
	return findOrgRoot(node.pid); // Recursively find the parent's root
}
